import time
from flask import Flask, jsonify, render_template, send_from_directory,abort
import os
import json
import logging
import threading
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
class Server:
    '''
        控制器
    '''
    WWW_ROOT='www'
    def __init__(self, rtk_driver,port=80):
        '''
        :param type:
        :param port:
        :param buffer_len:
        '''
        self.rtk_driver=rtk_driver
        self.port=port
        self.InitServer()
        

    def InitServer(self):
        '''初始化http服务器'''
        self.app = Flask(__name__)
        self.app.add_url_rule('/targets', view_func=self.GetTargets)
        self.app.add_url_rule('/odoms', view_func=self.GetOdoms)
        t=threading.Thread(target=self.StartServer,args=())
        t.setDaemon(True)
        t.start()
        
    def StartServer(self):
        '''启动服务器'''
        self.app.run(host='0.0.0.0', port=self.port)

    def GetTargets(self):
        '''获取目标列表'''
        self.UpdateData()
        ret = {"targets": self.targets}
        return jsonify(ret)

    def GetOdoms(self):
        '''获取整个路径'''
        return jsonify(self.rtk_driver.buffer)


    def UpdateData(self):
        '''更新状态'''
        self.targets = []
        for target in self.rtk_driver.buffer.keys():
            if len(self.rtk_driver.buffer[target]) > 0: self.targets.append(self.rtk_driver.buffer[target][-1])


if __name__=='__main__':
    type={}
    s=None
    with open('config.json','r') as f: type=json.load(f)
    if type['mode']=='wifi': s=Server('wifi')
    else: s=Server('uart',type['port'])